require('./polyfill');

// 缓存模块
import * as Cache from './cache';
import cacheKeys from './cache-keys';

// 环境
export const env = {
    isIPad: /ipad/i.test(window.navigator.userAgent),
    isIphone: /iphone|ipad|ipod/i.test(window.navigator.userAgent),
    isWechat: /MicroMessenger/i.test(window.navigator.userAgent)
};

// 视口
export function setViewport() {
    var screenWidth = window.screen.width;
    var scale = 1, width = 'device-width';

    if (screenWidth < 300) {
        scale = 0.8;
    } else if (screenWidth >= 750 && screenWidth < 1200) {
        scale = 1.6;
    } else if (screenWidth >= 1200) {
        scale = 2;
    }

    if (scale !== 1) {
        width = screenWidth / scale;

        var content = `width=${width}, initial-scale=${scale}, maximum-scale=${scale}, minimum-scale=${scale}, user-scalable=no`;
        var viewport = document.querySelector('meta[name=viewport]');
        viewport.setAttribute('content', content);
    }
}

// 标题
export function setTitle(title) {
    document.title = title;
    
    if (env.isIphone && env.isWechat) {
        var body = document.getElementsByTagName('body')[0];
        var iframe = document.createElement('iframe');
        iframe.setAttribute('src', '/favicon.ico');

        iframe.addEventListener('load', function() {
            setTimeout(function() {
                iframe.removeEventListener('load');
                document.body.removeChild(iframe);
            }, 0);
        });
        document.body.appendChild(iframe);
    }
}

// 判断
export const is = {
    has(val) {
        return !!val;
    },
    not(val) {
        return !val;
    },
    empty(val) {
        return val === '';
    },
    equal(v1, v2) {
        return v1 === v2;
    },
    qq(val) {
      return val &&　/^[1-9]\d{4,12}$/.test(val);
    },
    name(val) {
      return val &&　/^[A-Za-z0-9\u4E00-\u9FA5_]{2,14}$/.test(val);
    },
    mobile(val) {
        return val && /(^(13\d|14[57]|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/.test(val);
    },
    fifteen(val) {
        return val && /^[\d\-_+]{2,15}$/.test(val);
    },
    email(val) {
        return val && /^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(val);
    },
    password(val) {
        return val && val.length && val.length > 5 && !/^\d+$/.test(val);
    }
};

// requestAnimationFrame
var requestAnimationFrame = (function() {
    return  window.requestAnimationFrame   ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

/**
 * scrollTo position
 * @param container: the container current scrollTop
 * @param element: the target scrollY property
 * @param offset: the offset padding
 * @param duration: total animation time
 * @param easing: easing equation to use
 */
export const scrollTo = function (container, element, offset = 0, duration = 500, easing = 'easeOutSine') {
    var scrollY = container.scrollTop,
        scrollTargetY = getPos(element).top + offset,
        currentTime = 0,
        startTime = 0;

    // add animation loop
    function tick() {
        currentTime = Date.now();

        var p = (currentTime - startTime) / duration;
        var t = easingEquations[easing](p);

        if (p < 1) {
            requestAnimationFrame(tick);

            container.scrollTop = scrollY + ((scrollTargetY - scrollY) * t);
        } else {
            container.scrollTop = scrollTargetY;
        }
    }

    // call it once to get started
    startTime = Date.now();
    tick();
};

/**
 * get element position of screen
 * @param element
 * @returns {number}
 */
/**
 * 
 * @param element
 * @returns {{ top, left }}
 */
export const getPos = function(element) {
    var left = 0,
        top = 0;
    
    if (!element) return { top, left };
    
    do {
        left += element.offsetLeft;
        top += element.offsetTop;
    } while ( element = element.offsetParent );

    return { top, left };
};

// 加载js
var write = document.write;
export const loadJs = function (urls, callback, fallback) {
    if (typeof urls !== 'string' && !Array.isArray(urls)) return;
    var arrays = Array.isArray(urls) ? urls : [urls];
    if (!arrays.length) return;

    var src = arrays.shift();
    
    document.write = function(content) {
        var matches = /<script[^>]+src="([^"]+)"/i.exec(content);

        if (matches && matches[1]) {
            arrays.push(matches[1]);
        } else {
            var html = document.body.innerHTML;
            document.body.innerHTML = html + content;
        }
    };
    
    appendScript(src, function () {
        if (arrays.length) {
            loadJs(arrays, callback);
        } else {
            document.write = write;
            if (callback && typeof callback === 'function') {
                callback();
            }
        }
    }, function () {
        unloadJs(src, function () {
            console.error('Failed to load: ' + src);
            
            document.write = write;
            if (fallback && typeof fallback === 'function') {
                fallback();
            }
        });
    });
};

export const unloadJs = function (urls, callback) {
    if (typeof urls !== 'string' && !Array.isArray(urls)) return;
    var arrays = Array.isArray(urls) ? urls : [urls];
    if (!arrays.length) return;
    arrays = arrays.map(u => u.replace(/^[^/]*?\/\//, ''));

    var scripts = document.body.querySelectorAll('script');
    for (let script of scripts) {
        let src = script.getAttribute('src');
        if (!!~arrays.indexOf(src)) {
            document.body.removeChild(script);
        }
    }
    
    if (callback && typeof callback === 'function') {
        callback();
    }
};

function appendScript(src, callback, fallback) {
    if (existsScript(src)) {
        if (callback && typeof callback === 'function') callback();
        return;
    }

    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.src = src;
    if (callback && typeof callback === 'function') script.onload = callback;
    if (fallback && typeof fallback === 'function') script.onerror = fallback;
    
    document.body.appendChild(script);
}

function existsScript(src) {
    var scripts = document.body.querySelectorAll('script');
    for (let script of scripts) {
        if (script.getAttribute('src') === src) {
            return true;
        }
    }
    
    return false;
}

// 格式化日期时间
Date.prototype.format = function (format) {
    var p = {
        'm+': String(this.getMonth() + 1),  //月份
        'd+': String(this.getDate()),       //日
        'h+': String(this.getHours()),      //小时
        'n+': String(this.getMinutes()),    //分
        's+': String(this.getSeconds())     //秒
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (String(this.getFullYear())).substr(4 - 2 * RegExp.$1.length));
    }

    for (var i in p) {
        if (new RegExp('(' + i + ')').test(format)) {
            var v = RegExp.$1.length === 1 ? p[i] : ('00' + p[i]).substr(p[i].length);
            format = format.replace(RegExp.$1, v);
        }
    }

    return format;
};

// 全局配置
var globalConfigs;
if (process.env.NODE_ENV === 'development') {
    globalConfigs = process.env.globalConfigs;
} else {
    globalConfigs = window.globalConfigs;
}

var cache_keys = cacheKeys(globalConfigs.BRAND.cache);

export {
    Cache,
    cache_keys,
    globalConfigs
};